package com.qinglei.recoup.longconn.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.AdaptiveRecvByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.FixedRecvByteBufAllocator;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 设备服务提供方
 */
@Service
@Slf4j
public class DeviceNettyServer implements Runnable, InitializingBean, DisposableBean {
    @Value("${recoup.longconn.server.port}")
    private int port;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private Channel channel;
    private Thread server;


    @Autowired
    NettyServerInitializer nettyServerInitializer;

    @Override
    public void afterPropertiesSet() throws Exception {
        server = new Thread(this);
        server.start();
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("destroy server resources");
        if (null == channel) {
            System.out.println("server channel is null");
        }
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        channel.closeFuture().syncUninterruptibly();
        bossGroup = null;
        workerGroup = null;
        channel = null;
    }

    @Override
    public void run() {
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup);
            b.channel(NioServerSocketChannel.class);
            b.childHandler(nettyServerInitializer);
            b.childOption(ChannelOption.SO_REUSEADDR, true);
            b.childOption(ChannelOption.TCP_NODELAY, true);
            b.childOption(ChannelOption.SO_KEEPALIVE, true);
//            b.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(100));
//            b.childOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(100));
//            b.option(ChannelOption.RCVBUF_ALLOCATOR,
//                    new AdaptiveRecvByteBufAllocator(DEFAULT_MIN_SIZE, DEFAULT_INITIAL_SIZE, DEFAULT_MAX_SIZE))

            // 服务器绑定端口监听
            ChannelFuture f = b.bind(port).sync();
            log.info("Tcp server started on port: {}", port);
            // 监听服务器关闭监听
            f.channel().closeFuture().sync();
            channel = f.channel();
        } catch (InterruptedException e) {
            log.error("server exception", e);
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    /**
     * 发送下行消息给所有客户端
     * @param funcCode
     * @param body
     * @return
     */
    public int sendMessageAllClient(String funcCode, String body) {
        return nettyServerInitializer.sendMessageAllClient(funcCode, body);
    }

    /**
     * 发送下行消息给指定客户端
     * @param snList
     * @param funcCode
     * @param body
     * @return
     */
    public int sendMessage2Client(List<String> snList, String funcCode, String body) {
        return nettyServerInitializer.sendMessage2Client(snList, funcCode, body);
    }
}
